package com.ias.agdis_r.activity.message;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import com.android.volley.NoConnectionError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.ias.agdis_r.R;
import com.ias.agdis_r.activity.BaseKeyActivity;
import com.ias.agdis_r.activity.MainActivity;
import com.ias.agdis_r.db.MyBeanTempDBHelper;
import com.ias.agdis_r.db.message.MyMessageBean;
import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.manager.DataManager;
import com.ias.agdis_r.manager.EffectManager;
import com.ias.agdis_r.manager.MessageManager;
import com.ias.agdis_r.module.MessageModel;
import com.ias.agdis_r.module.RestfulUri;
import com.ias.agdis_r.netservice.listener.MessageSendSuccessListener;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.response.BaseResponse;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.response.BaseResponseHeader;
import com.ias.agdis_r.terminalmanager.restful.message.endpoint.request.WorkingMsgUpRequest;
import com.ias.agdis_r.terminalmanager.restful.message.endpoint.response.WorkingMsgUpResponse;
import com.ias.agdis_r.util.S;
import com.ias.agdis_r.util.SecurityUtil;
import com.ias.agdis_r.util.date.PrettyDataFormaterUtil;
import com.ias.agdis_r.fragment.box.BoxTabMessage;
import com.ias.agdis_r.util.flight.UiUtil;
import com.ias.agdis_r.volley.GsonRequest;
import com.ias.agdis_r.volley.callback.BaseOnVolleyErrorAdapter;
import com.ias.agdis_r.volley.callback.BaseOnVolleyErrorListener;
import com.ias.agdis_r.volley.callback.BaseOnVolleySuccessListener;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * 接收到短语详情，需要传入EXTRA：TGN
 * 
 * @author qibo.yu
 * @version 2015年8月25日 上午8:53:44
 **/
public class MessageDetailsActivity extends BaseKeyActivity {

	public static final String EXTRA_MESSAGE_TGN = "ge com.ias.agdis_r.message.tgn";

	private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.CHINA);

	MyBeanTempDBHelper<MyMessageBean> dbHelper;
	private String _id;

	private TextView title;
	private TextView sdt, fln, sem, stm, txt;
	private Button btnReceipt, btnReply;

	private String fke, tnb, tgn, aod, fst,ack;

	private RequestQueue requestQueue;

	private BaseOnVolleySuccessListener<WorkingMsgUpResponse> successListener = new BaseOnVolleySuccessListener<WorkingMsgUpResponse>() {
		@Override
		public void onRequestSuccess(WorkingMsgUpResponse response) {
			EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK, getString(R.string.receiptSucceed), false);
			fst = "Y";
			validateReceiptBtn(ack);

			String sql = "update " + dbHelper.getTableName() + " set fst = 'Y' where _id = '" + _id
					+ "'";
			SQLiteDatabase db = dbHelper.getWritableDatabase();
			db.execSQL(sql);
			db.close();
			Log.d("C_db", "execute sql: "+sql);
			UiUtil.removeLoadingUiIfExist(MessageDetailsActivity.this);
		}

		@Override
		public void onRequestFailed(BaseResponseHeader header) {
			EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, getString(R.string.serviceError), false);
			UiUtil.removeLoadingUiIfExist(MessageDetailsActivity.this);
		}
	};

	private BaseOnVolleyErrorListener errorListener = new BaseOnVolleyErrorAdapter() {
		@Override
		public void onErrorOccurred(VolleyError e) {
			String msg = getString(R.string.error);
			if (e instanceof TimeoutError) {

				msg = DataBaseManager.getInstance().getContext().getString(R.string.request_err_timeout);
			} else if (e instanceof ServerError) {
				//显示接收消息异常
				msg = DataBaseManager.getInstance().getContext().getString(R.string.request_err_servererror);
			} else if (e instanceof NoConnectionError) {
				msg = DataBaseManager.getInstance().getContext().getString(R.string.request_err_noconnection);
			}
			EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, msg, false);
			UiUtil.removeLoadingUiIfExist(MessageDetailsActivity.this);

		}

	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_message_details);

		requestQueue = Volley.newRequestQueue(this);

		initactionBar();
		setTitle(R.string.MessageDetailsActivity);

		this.dbHelper = new MyBeanTempDBHelper<MyMessageBean>(this, MyMessageBean.class);
		tgn = getIntent().getStringExtra(EXTRA_MESSAGE_TGN);

		if (S.isEmpty(tgn)) {
			finish();
		} else {
			initView();
			bindData();
		}
	}

	private void bindData() {

		SQLiteDatabase db = dbHelper.getReadableDatabase();
		String sql = "select sdt,stm,sem,mtn,fln,txt,ack,mti,_id,readed,fke,tnb,tgn,aod,fst from "
				+ dbHelper.getTableName() + " where tgn = '" + tgn + "' and sem is not null and sem !=''";
		Cursor cursor = db.rawQuery(sql, null);
		if (cursor.getCount() > 0) {
			cursor.moveToFirst();
			try {
				sdt.setText(PrettyDataFormaterUtil.formateDate(DATE_FORMAT.parse(cursor.getString(0)),
						MessageDetailsActivity.this));
			} catch (ParseException e) {
				sdt.setText(cursor.getString(0));
			}
			try {
				stm.setText(PrettyDataFormaterUtil.formateDate(DATE_FORMAT.parse(cursor.getString(1)),
						MessageDetailsActivity.this));
			} catch (ParseException e) {
				stm.setText(cursor.getString(1));
			}
			fln.setText(cursor.getString(4));
			sem.setText(cursor.getString(2));
			txt.setText(cursor.getString(5));

			this.fke = cursor.getString(10);
			this.tnb = cursor.getString(11);
			this.tgn = cursor.getString(12);
			this.aod = cursor.getString(13);
			this.fst = cursor.getString(14);
			this.ack = cursor.getString(6);
			this._id = cursor.getString(8);

			validateReadedField(cursor.getString(9));
			validateReplyBtn(cursor.getString(7));
			validateReceiptBtn(ack);
			cursor.close();
			db.close();
		} else {
			EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, getString(R.string.notFoundMessage), false);
		}

	}

	private void validateReceiptBtn(final String ack) {
		if ("Y".equals(ack) && !"Y".equals(fst)) {
			btnReceipt.setEnabled(true);
			btnReceipt.setText(getString(R.string.receipt));
			btnReceipt.setVisibility(View.VISIBLE);
			btnReceipt.setEnabled(true);
			btnReceipt.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					// 来源于老版本（回执发送成功失败状态检测？？成功后fst字段是否需要修正）
					String sConfirmGwsmMsg = MessageManager.getInstance().confirmGwsmMsg(tgn);


					//确认消息取系统时间
					SimpleDateFormat adfTime = new SimpleDateFormat("HHmm");
					Date date = new Date();
					String sdt = adfTime.format(date);

					WorkingMsgUpRequest msgBean = new WorkingMsgUpRequest();
					msgBean.setHeader(SecurityUtil.getCommonRequestHeaderObject(MessageModel.GWRP));
					msgBean.setMt(MessageModel.GWRP);
					msgBean.setTgn(tgn);
					msgBean.setTst("R");
					msgBean.setSdt(sdt);

					UiUtil.showLoadingUi(MessageDetailsActivity.this);
					Request<WorkingMsgUpResponse> request = null;
					try {
						request = new GsonRequest<WorkingMsgUpResponse>(RestfulUri.getUri(MessageModel.GWRP), WorkingMsgUpResponse.class, DataManager.getInstance().getMapper().writeValueAsString(msgBean), successListener, errorListener);
					} catch (IOException e) {
						e.printStackTrace();
						return;
					}
					requestQueue.add(request);



//					ServiceManage.getInstance().sendMessage(sConfirmGwsmMsg, null, new MessageSendSuccessListener() {
//
//						@Override
//						public void onSuccess() {
//							EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK, "回执成功", false);
//							fst = "Y";
//							validateReceiptBtn(ack);
//
//							String sql = "update " + dbHelper.getTableName() + " set fst = 'Y' where _id = '" + _id
//									+ "'";
//							SQLiteDatabase db = dbHelper.getWritableDatabase();
//							db.execSQL(sql);
//							db.close();
//						}
//					});
				}
			});
		} else if ("Y".equals(fst)) {
			btnReceipt.setEnabled(false);
			btnReceipt.setOnClickListener(null);
			btnReceipt.setText(getString(R.string.receipted));
			btnReceipt.setEnabled(false);
		} else {
			btnReceipt.setEnabled(false);
			btnReceipt.setOnClickListener(null);
			btnReceipt.setText(getString(R.string.noReceipt));
			btnReceipt.setVisibility(View.GONE);
		}

	}

	private void validateReplyBtn(String mti) {
		if ("02".equals(mti) || "10".equals(mti)) {
			btnReply.setEnabled(true);
			btnReply.setText(getString(R.string.reply));
			btnReply.setVisibility(View.VISIBLE);
			btnReply.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					Intent intent = new Intent(MessageDetailsActivity.this, MessageSendActivity.class);
					intent.putExtra(MessageSendActivity.EXTRA_TGN, tgn);
					intent.putExtra(MessageSendActivity.EXTRA_TXT, txt.getText().toString());
					if (S.isEmpty(fke)) {
						intent.putExtra(MessageSendActivity.EXTRA_TYPE, MessageSendActivity.TYPE_NORMAL);
					} else {
						intent.putExtra(MessageSendActivity.EXTRA_TYPE, MessageSendActivity.TYPE_TASK);
						intent.putExtra(MessageSendActivity.EXTRA_TNB, tnb);
						intent.putExtra(MessageSendActivity.EXTRA_FKE, fke);
						intent.putExtra(MessageSendActivity.EXTRA_FLN, fln.getText().toString());
						intent.putExtra(MessageSendActivity.EXTRA_AOD, aod);
					}
					startActivity(intent);
				}
			});
		} else {
			btnReply.setEnabled(false);
			btnReply.setText(getString(R.string.cantReply));
			btnReply.setVisibility(View.GONE);
		}

	}

	private void validateReadedField(String readed) {
		// 如果是未读状态
		if (S.isEmpty(readed) || "0".equals(readed)) {
			readMessage();
			DataManager.getInstance().subtractUnCheckNumber();
			setResult(BoxTabMessage.RESULTCODE);
		}
		// 如果是忽略状态
		else if ("2".equals(readed)){
			readMessage();
		}
	}

	private void readMessage(){
		// 修改为已读状态
		String sql = "update " + dbHelper.getTableName() + " set readed = '1' where _id = '" + _id + "'";
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		db.execSQL(sql);
		Log.d("C_sql", sql);
		db.close();
	}

	private void initView() {
		this.sdt = (TextView) this.findViewById(R.id.msg_sdt);
		this.fln = (TextView) this.findViewById(R.id.msg_fln);
		this.sem = (TextView) this.findViewById(R.id.msg_sem);
		this.stm = (TextView) this.findViewById(R.id.msg_stm);
		this.txt = (TextView) this.findViewById(R.id.msg_txt);

		this.btnReceipt = (Button) this.findViewById(R.id.msg_btn_receipt);
		this.btnReply = (Button) this.findViewById(R.id.msg_btn_reply);

	}

	@Override
	public void setTitle(CharSequence title) {
		this.title.setText(title);
		super.setTitle(title);
	}

	@Override
	public void setTitle(int titleId) {
		this.setTitle(getString(titleId));
	}

	@SuppressLint("InflateParams")
	private void initactionBar() {
		final Activity context = this;

		ActionBar actionBar = getActionBar();

		actionBar.setCustomView(LayoutInflater.from(this).inflate(R.layout.actionbar_back_and_home, null));
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
		actionBar.setDisplayShowCustomEnabled(true);

		this.title = (TextView) findViewById(R.id.txt_title);

		ImageView back = (ImageView) findViewById(R.id.action_back);
		back.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				finish();
			}
		});

		ImageView home = (ImageView) findViewById(R.id.action_home);
		home.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(context, MainActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
			}
		});
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(null != requestQueue)
		requestQueue.stop();
	}
}
